package com.spring.listener;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;

import com.spring.annoation.AnnoationInit;
import com.spring.annoation.Interceptorn;
import com.spring.remote.Invoke;
import com.spring.task.TaskDispatcher;

@Component
public class SpringContext implements ApplicationContextAware {

	private static ApplicationContext applicationContext;
	private static Set<Object> classSet = new HashSet<Object>();// 存放control
	private static Set<Object> interceSet = new HashSet<>();
	public static Map<String, Invoke> mapUri = new HashMap<String, Invoke>();// 匹配uri


	/**
	 * 实现ApplicationContextAware接口的回调方法，设置上下文环境
	 */
	public void setApplicationContext(ApplicationContext applicationContext) {
		SpringContext.applicationContext = applicationContext;
		//
		TaskDispatcher.start();
		// 加载所有control
		Map<String, Object> beans = applicationContext.getBeansWithAnnotation(Controller.class);
		for (Object bean : beans.values()) {
			classSet.add(bean);
		}
		// 加载所有interceptor
		Map<String, Object> interceptor = applicationContext.getBeansWithAnnotation(Interceptorn.class);
		for (Object bean : interceptor.values()) {
			interceSet.add(bean);
		}
		//加载所有control的dispatcher
		SpringContext.getClassSet().forEach(entry -> {
			try {
				mapUri = AnnoationInit.parseMethod(entry);
			} catch (Exception e) {
				e.printStackTrace();
			}
		});

	}

	public static ApplicationContext getApplicationContext() {
		return applicationContext;
	}

	public static Set<Object> getClassSet() {
		return classSet;
	}
	
	public static Set<Object> getInterceSet() {
		return interceSet;
	}

	/**
	 * 获取对象
	 * 
	 * @return Object 一个以所给名字注册的bean的实例 (service注解方式，自动生成以首字母小写的类名为bean name)
	 */
	public static Object getBean(String name) throws BeansException {
		return applicationContext.getBean(name);
	}

}
